﻿using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using System.Text;

namespace HzyAdmin.Controllers
{
    using Toolkit;

    public class HomeController : Controller
    {

        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 异常拦截
        /// </summary>
        /// <returns></returns>
        public IActionResult Error()
        {
            var _IExceptionHandlerFeature = HttpContext.Features.Get<IExceptionHandlerFeature>();
            var _Error = _IExceptionHandlerFeature?.Error;

            var IsAjaxRequest = Tools.IsAjaxRequest;

            //判断是否是自定义异常类型
            if (_Error is MessageBox)
            {
                HttpContext.Response.StatusCode = 200;
                var _ErrorModel = ErrorModel.Model;

                if (IsAjaxRequest)
                {
                    if (_ErrorModel.status == (int)EMsgStatus.Custom60)
                    {
                        return Json(_ErrorModel.Data);
                    }
                    return Json(ErrorModel.Model);
                }

                _ErrorModel = new ErrorModel(_Error.Message);
                var _Script = $"<script type='text/javascript'>alert({_ErrorModel.msg.Trim()})</script>";
                return Content(_Script, "text/html;charset=utf-8;");
            }
            else
            {
                Tools.Log.WriteLog(_Error, HttpContext.Connection.RemoteIpAddress.ToString());//log4net 写入日志到 txt
                var errorModel = new ErrorModel(_Error);
                if (IsAjaxRequest)
                {
                    return Json(errorModel);
                }
                return View(AppConfig.ErrorPageUrl, errorModel);
                //return View("~/Views/Shared/Error.cshtml", error);
            }

        }


    }
}
